﻿using System;
using System.Collections.Generic;
using System.Drawing.Printing;
using System.Linq;
using System.Windows.Forms;
using Infragistics.Win.UltraWinGrid;
using POS.BusinessComponents;
using POS.BusinessEntities;

namespace POS.UI.Mantenimientos
{
    public partial class MantEstacionesForm : MantForm
    {
        #region Constructors

        public MantEstacionesForm()
        {
            InitializeComponent();
        }

        #endregion

        #region Declarations
        
        private int selectedId;
        private const string idColumn = "Id";
        private const string nameColumn = "Nombre";

        private readonly BCEstacion bc = new BCEstacion();

        #endregion

        #region Event Handlers

        private void MantEstacionesForm_Load(object sender, EventArgs e)
        {
            LoadList();
            LoadComboBoxes();
            toolStrip.ItemClicked += toolStrip_ItemClicked;

            consecutivoFacturaTextBox.Format = IntegerFormat;
            consecutivoDevolucionTextBox.Format = IntegerFormat;
        }

        private void toolStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            switch (e.ClickedItem.Text)
            {
                case NewText:
                    New();
                    break;
            }
        }

        private void grid_InitializeLayout(object sender, InitializeLayoutEventArgs e)
        {
            ConfigureGrid((UltraGrid)sender);
        }

        private void grid_AfterRowActivate(object sender, EventArgs e)
        {
            selectedId = (int)grid.ActiveRow.Cells[idColumn].Value;
            UnPack((BEEstacion)grid.ActiveRow.ListObject);
        }
        
        private void grid_AfterSelectChange(object sender, AfterSelectChangeEventArgs e)
        {
            EnableDisable();
        }

        #endregion

        #region Methods: Non-Public

        protected new static void ConfigureGrid(UltraGridBase listGrid)
        {
            MantForm.ConfigureGrid(listGrid);
            
            foreach (var col in listGrid.DisplayLayout.Bands[0].Columns)
                col.Hidden = true;

            listGrid.DisplayLayout.Bands[0].Columns[nameColumn].Hidden = false;
        }

        protected override bool ValidateInput()
        {
            var name = nombreTextBox.Text.Trim();

            if (string.IsNullOrEmpty(name))
            {
                ShowError("Debe ingresar el nombre");
                nombreTextBox.Focus();
                return false;
            }
            if (!IsUniqueName(name) && selectedId == 0)
            {
                ShowError("El nombre seleccionado ya ha sido ingresado");
                nombreTextBox.Focus();
                return false;
            }
            return true;
        }

        protected bool IsUniqueName(string name)
        {
            foreach(var item in bc.GetList(name))
                if (item.Nombre == name)
                    return false;
            return true;
        }

        private void New()
        {
            ClearControls(Controls);
            nombreTextBox.Focus();
            selectedId = 0;
            ClearGridSelection();
        }

        protected override void Save()
        {
            if (ValidateInput())
            {   
                bc.Save(Pack());
                New();
                LoadList();
            }
        }

        protected override void Delete()
        {
            if (ShowQuestion("¿Está seguro de querer eliminar la estación seleccionada?"))
            {
                new BCEntidad(TipoEntidad.Estacion).Delete(selectedId);
                LoadList();
                ClearControls(Controls);
                ClearGridSelection();
                grid.Select();
            }
        }

        private void LoadComboBoxes()
        {
            var printers = LoadInstalledPrinters();
            // duplicates datasource to make comboboxes independent
            var devolucionesPrinters = new string[printers.Count];
            printers.CopyTo(devolucionesPrinters,0);
            
            facturasComboBox.DataSource = printers;
            devolucionesComboBox.DataSource = devolucionesPrinters;

            for (var i = 1; i < 10; i++)
                tiquetesComboBox.Items.Add("LPT" + i);
            for (var i = 1; i < 10; i++)
                tiquetesComboBox.Items.Add("COM" + i);
            tiquetesComboBox.Items.AddRange(printers.ToArray());

            facturasComboBox.SelectedIndex = -1;
            devolucionesComboBox.SelectedIndex = -1;
            tiquetesComboBox.SelectedIndex = -1;
        }

        private static IList<string> LoadInstalledPrinters()
        {
            var printers = new List<string>();
            foreach (string printer in PrinterSettings.InstalledPrinters)
                printers.Add(printer);

            return printers;
        }

        private void LoadList()
        {
            grid.DataSource = bc.GetList("");
            ClearGridSelection();
        }

        private void ClearGridSelection()
        {
            grid.Selected.Rows.Clear();
            grid.ActiveRow = null;
            EnableDisable();
        }

        private void EnableDisable()
        {
            toolStrip.Items[DeleteText].Enabled = grid.Selected.Rows.Count > 0;
        }

        private BEEstacion Pack()
        {
            int consecutivoFactura;
            int consecutivoDevolucion;
            if (!int.TryParse(consecutivoFacturaTextBox.Text, out consecutivoFactura))
                consecutivoFactura = 1;
            if (!int.TryParse(consecutivoDevolucionTextBox.Text, out consecutivoDevolucion))
                consecutivoDevolucion = 1;

            var entity = new BEEstacion
                {
                     Id = selectedId,
                     Nombre = nombreTextBox.Text.Trim(),
                     ConsecutivoFactura = consecutivoFactura,
                     ConsecutivoDevolucion = consecutivoDevolucion,
                     ImpresoraFacturas = facturasComboBox.Text,
                     ImpresoraDevoluciones = devolucionesComboBox.Text,
                     ImpresoraTiquetes = tiquetesComboBox.Text
                };
            return entity;
        }

        private void UnPack(BEEstacion entity)
        {
            facturasComboBox.SelectedIndex = -1;
            devolucionesComboBox.SelectedIndex = -1;
            tiquetesComboBox.SelectedIndex = -1;
            
            nombreTextBox.Text = entity.Nombre;
            consecutivoFacturaTextBox.Text = entity.ConsecutivoFactura.ToString(IntegerFormat);
            consecutivoDevolucionTextBox.Text = entity.ConsecutivoDevolucion.ToString(IntegerFormat);
            facturasComboBox.Text = entity.ImpresoraFacturas;
            devolucionesComboBox.Text = entity.ImpresoraDevoluciones;
            tiquetesComboBox.Text = entity.ImpresoraTiquetes;
        }

        #endregion
        
    }
}
